<template>
  <div class='m-invent_detail'>
    <!-- top -->
    <div class='m-invent_detail_top'>
      <div class="title" style='padding-left: 15px;font-size: 20px;font-weight: bold;'>进货单详情</div>
      <el-row type='flex' justify='end'>
        <el-col :span='3'>
          <el-button @click='showCostDialog'>收支项目</el-button>
        </el-col>
        <el-col :span='3'>
          <el-button @click='selectAttr'>选择属性</el-button>
        </el-col>
        <el-col :span='3'>
          <el-button @click='addAttr'>添加属性</el-button>
        </el-col>
        <el-col :span='3'>
          <el-button @click='showGoodsDialgo'>添加商品</el-button>
        </el-col>
        <el-col :span='3'>
          <el-button type='primary' @click='confirm' >保存</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- form -->
    <el-form class="form" ref='form' :model="form" :rules='rules'>
      <el-form-item class='form-item'  label="进货单号：" prop='no'>
        <el-input type="text" placeholder="请输入进货单号" v-model="form.no"></el-input>
      </el-form-item>
      <el-form-item class='form-item'  label="进货日期：" prop='time'>
        <el-date-picker
          v-model="form.time"
          type="date"
          value-format='timestamp'
          placeholder="请选择进货时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item  class='form-item' label="进货总额：">
        {{ allPrice | filterPrice }}
      </el-form-item>
      <el-form-item  class='form-item' label="供货单位：" prop='bill'>
        <div @click='openSeletList'>
          {{ billName || '点击选择供货单位' }}
        </div>
      </el-form-item>
      <el-form-item v-if='!isAdd' class='form-item' label="最后修改人：" >
        {{ modifier_name }}
      </el-form-item>
      <el-form-item v-if='!isAdd' class='form-item' label="最后修改时间：" >
        {{ modify_time }}
      </el-form-item>
    </el-form>
    <attr-form ref='attrForm' type='6' />
    <!-- table -->
    <a-table :data='data' :cols='tableKeys'>
      <el-table-column align="center" label="操作" width='180' slot='ahead'>
        <template slot-scope="scope">
          <div>
            <el-button size='mini' @click='choose(scope.$index)'>详情</el-button>
            <el-button size='mini' @click='deleteGoods(scope.$index)'>删除</el-button>
            <el-button size='mini' @click='showCostDetail(scope.row)'>收支</el-button>
          </div>
        </template>
      </el-table-column>
    </a-table>

    <goods-dialog ref='goodsDialog' @update='getDetail' @getData='getGoods' :selectSkuIds='selectSkuIds' :id='id' :isAddOrder='isAdd' />
    <sup-select-list ref='supSelectList' @handelSupSelectList="handelSupSelectList"  type='1' />
    <cost-detail-dialog ref='costDetailDialog' :title='billName' :id='id' :isAdd='isAdd' />
    <cost-select-list-dialog ref='costSelectListDialog' :title='billName' :id='id' :isAdd='isAdd' />
  </div>
</template>

<script>
import AttrForm from '@/components/business/Form'
import goodsDialog from '@/module/invent/components/goodsDialog'
import supSelectList from '@/module/invent/components/supSelectList'
import costDetailDialog from '@/module/invent/components/costDetailDialog'
import costSelectListDialog from '@/module/invent/components/costSelectListDialog'
import { mapMutations } from 'vuex'

export default {
  name: 'invent_create',

  components: {
    AttrForm,
    costDetailDialog,
    costSelectListDialog,
    supSelectList,
    goodsDialog
  },

  data() {
    return {
      tableKeys: [
        { prop: 'name', label: '品名', minWidth: '100' },
        { prop: 'title', label: 'sku 属性', minWidth: '100' },
        { prop: 'price', label: '价格', minWidth: '100', filter: window.$tools.filterPrice },
        { prop: 'number', label: '数量', minWidth: '100' },
        { prop: 'allPrice', label: '总金额', minWidth: '100', filter: window.$tools.filterPrice }
      ],
      data: [],
      form: {
        no: '',
        time: '',
        bill: ''
      },
      billName: '',
      rules: {
        no: [
          { required: false, message: '请输入进货单号', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '请选择进货日期', trigger: 'blur' }
        ],
        bill: [
          { required: true, message: '请选择供货单位', trigger: 'blur' }
        ]
      },
      ifRequesting: false,
      type: 'add',
      isAdd: true,
      // 进货总额
      allPrice: 0,
      modify_time: '',
      modifier_name: '',
      id: '',
      // 选中的 skuid 数组
      selectSkuIds: []
    }
  },

  async created() {
    const { id } = this.$route.query
    this.id = id
    await this.getAttributes()
    if (!id) {
      this.isAdd = true
    } else {
      this.isAdd = false
      this.getDetail()
    }
  },

  methods: {
    ...mapMutations(['setTabRoutes']),

    async getDetail() {
      const { code, data } = await this.$api.inventGetBuyingBillInfo({ aId: this.id })
      if (code === 0) {
        this.form.no = data.no
        this.form.time = data.date + '000'
        this.form.bill = data.intent_id
        this.billName = data.intent_name
        this.modify_time = window.$tools.filterTime(data.modify_time)
        this.modifier_name = data.modifier_name
        this.$refs.supSelectList.selectVal(data.intent_id)
        // sku 的 sku_id
        this.selectSkuIds = data.skus.map(v => v.id)
        this.data = this.formatSkusFromDetail(data.skus)
        this.computingAllPrice()
        this.$refs.attrForm.$formatDetail(data)
      }
    },

    async create() {
      this.ifRequesting = true
      const { time, no, bill } = this.form
      const params = {
        aFirmId: this.aFirmId,
        aId: this.id || '',
        aMerchantId: this.aFirmId,
        aAttrs: this.$refs.attrForm.$formatOutputData()
      }
      if (this.isAdd) {
        params.aSkus = this.formatSkusData()
      }
      if (time) params.aDate = (parseInt(time, 10) / 1000)
      if (bill) params.aIntentId = bill
      if (no) params.aNo = no
      const { code } = await this.$api[this.isAdd ? 'inventCreateBill' : 'inventModifyBill'](params)
      this.ifRequesting = false
      if (code === 0) {
        this.__notify(this.isAdd ? '添加成功' : '修改成功')
        this.setTabRoutes({ type: 'add', obj: this.getRouterInfoAccordingName('invent_list') })
        this.$router.push({ name: 'invent_list' })
      }
    },

    confirm() {
      if (this.ifRequesting) return
      this.$refs.form.validate((valid) => {
        if (!valid) return
        this.create()
      })
    },

    reset() {
      this.$refs.form.resetFields()
    },

    // attr
    async getAttributes() {
      const { code, data } = await this.$api.utilsGetAllClasses({
        aMerchantId: this.aFirmId,
        aType: '6'
      })
      if (code === 0) {
        this.$refs.attrForm.$formatAttrAndClassData(data.list)
      }
    },

    selectAttr() {
      this.$refs.attrForm.$openSelectAttrBox()
    },

    addAttr() {
      this.$refs.attrForm.$openCreateAttrBox()
    },

    showGoodsDialgo() {
      this.$refs.goodsDialog.$show()
    },

    openSeletList() {
      this.$refs.supSelectList.$show()
    },

    choose(i) {
      this.$refs.goodsDialog.set(this.data[i])
      this.$refs.goodsDialog.$show('edit', i)
    },

    showCostDetail({ id }) {
      if (this.isAdd) return this.__notify('提示', '请保存进货单后，再添加收支项目', 'info')
      this.$refs.costDetailDialog.$show(id)
    },

    showCostDialog() {
      if (this.isAdd) return this.__notify('提示', '请保存进货单后，再添加收支项目', 'info')
      this.$refs.costSelectListDialog.$show()
    },

    async deleteGoods(i) {
      if (this.ifRequesting) return false
      this.__messageBox({
        title: '你确认要删除该单据吗？',
        successCallback: async () => {
          if (this.isAdd) {
            this.selectSkuIds.splice(i, 1)
            this.data.splice(i, 1)
            return 0
          }
          this.ifRequesting = true
          const { code } = await this.$api.invent_deleteBillSku({
            aId: this.id,
            aSkuId: this.data[i].id
          })
          this.ifRequesting = false
          if (code === 0) {
            this.selectSkuIds.splice(i, 1)
            this.data.splice(i, 1)
          }
          return code
        }
      })
    },

    handelSupSelectList({ id, name }) {
      console.log(this.form.bill)
      this.form.bill = id
      this.billName = name
    },

    computingAllPrice() {
      this.allPrice = 0
      this.data.forEach(v => {
        this.allPrice += parseFloat(v.price, 10)
      })
      this.allPrice = parseFloat(this.allPrice, 10)
    },

    getGoods(data, typeOrIndex) {
      if (typeOrIndex === 'add') {
        this.data.push({
          ...data,
          allPrice: parseFloat(data.price, 10) * data.aMats.length,
          number: data.aMats.length
        })
        this.selectSkuIds.push(data.sku_id)
      } else {
        this.data.splice(typeOrIndex, 1)
        this.data.splice(typeOrIndex, 0, {
          ...data,
          allPrice: parseFloat(data.price, 10) * data.aMats.length,
          number: data.aMats.length
        })
        this.selectSkuIds.splice(typeOrIndex, 1)
        this.selectSkuIds.splice(typeOrIndex, 0, data.sku_id)
      }
      this.computingAllPrice()
    },

    formatSkusData() {
      const data = []
      this.data.forEach(v => {
        data.push({
          aId: v.sku_id,
          aPrice: v.price,
          aMats: v.aMats.map(v2 => ({
            aId: v2.code,
            aMemo: v2.memo
          }))
        })
      })
      return data
    },

    formatSkusFromDetail(skus) {
      const obj = []
      skus.forEach(v => {
        obj.push({
          title: v.sku_name,
          name: v.goods_name,
          price: v.price,
          id: v.id,
          sku_id: v.id,
          number: v.mats.length,
          allPrice: parseFloat(v.price, 10) * v.mats.length,
          aMats: v.mats.map(v2 => ({
            code: v2.id,
            cacheCode: v2.id,
            isEdit: false,
            memo: v2.memo,
            cacheMemo: v2.memo
          }))
        })
      })
      return obj
    }
  }
}
</script>

<style lang='less'>
  .m-invent_detail {
    &_top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .el-row {
        flex: 1;
        text-align: center;
      }
      padding-bottom: 15px;
      margin-bottom: 15px;
      border-bottom: 1px solid #e5e5e5;
    }
    .addValue-list {
      display: flex;
      align-items: center;
      padding-bottom: 20px;
      .icon {
        margin-left: 20px;
      }
      &-child {
        padding-bottom: 10px;
      }
    }
    .form-data {
      width: 100%;
    }
    .form {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      &-item {
        display: flex;
        align-items: center;
        width: 50%;
        .el-form-item__label {
          width: 120px;
        }
        .el-form-item__content {
          flex: 1;
        }
      }
    }
  }
</style>